package cn.dsttl3.tupan.Ability.slice;

import cn.dsttl3.tupan.MyApp;
import cn.dsttl3.tupan.ResourceTable;
import cn.dsttl3.tupan.bean.baidu.AccessToken;
import cn.dsttl3.tupan.utils.AppUtils;
import cn.dsttl3.tupan.utils.DataUtils;
import com.google.gson.Gson;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.webengine.ResourceRequest;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebView;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.preferences.Preferences;
import ohos.miscservices.timeutility.Time;
import ohos.multimodalinput.event.KeyEvent;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import java.io.IOException;

public class LoginAbilitySlice extends AbilitySlice {

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_login);
        WebView webView = (WebView) findComponentById(ResourceTable.Id_login_wv);
        webView.getWebConfig().setJavaScriptPermit(true);
        webView.setWebAgent(new WebAgent(){
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                if (request.getRequestUrl().toString().startsWith("https://dsttl3.cn")){ // 这个链接是你所填写的 YOUR_REGISTERED_REDIRECT_URI 这里只写了开头
                    String code = request.getRequestUrl().toString().split("code=")[1];
                    String Access_token_url = new AppUtils().getAccessTokenUrl(code);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                OkHttpClient client = new OkHttpClient();
                                Request request = new Request.Builder().url(Access_token_url)
                                        .header("User-Agent","pan.baidu.com")
                                        .build();
                                Call call = client.newCall(request);
                                String accessTokenJson = call.execute().body().string();
                                AccessToken accessToken = new Gson().fromJson(accessTokenJson, AccessToken.class);
                                System.out.println(accessToken.getAccess_token());
                                getUITaskDispatcher().asyncDispatch(new Runnable() {
                                    @Override
                                    public void run() {
                                        Preferences preferences = new DataUtils().getPreferences(getApplicationContext());
                                        preferences.putString("token",accessToken.getAccess_token());
                                        preferences.flush();
                                        Intent intent1 = new Intent();
                                        Operation operation = new Intent.OperationBuilder()
                                                .withBundleName(MyApp.bundleName)
                                                .withAbilityName("cn.dsttl3.tupan.Ability.IndexAbility")
                                                .build();
                                        intent1.setOperation(operation);
                                        startAbility(intent1);
                                        terminateAbility();
                                    }
                                });
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    return false;
                }
                return super.isNeedLoadUrl(webView, request);
            }
        });
        webView.load(new AppUtils().getLoginUrl());
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * 防止误退出操作
     */
    boolean exit = true;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (exit){
            new ToastDialog(getContext()).setText("再次返回退出程序").show();
            exit = false;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Time.sleep(3000);
                    exit=true;
                }
            }).start();
            return true;
        }else {
            return false;
        }
    }
}
